package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.baidu.BaiDuAPIService;
import com.sky.baidu.BaiDuUtil;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.BaseException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.result.PageResult;
import com.sky.service.*;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private AddressBookService addressBookService;
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;
    @Autowired
    private BaiDuAPIService baiDuAPIService;
    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 用户下单
     * @param ordersSubmitDTO
     */
    @Override
    @Transactional
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 校验地址
        AddressBook addressBook = addressBookService.getById(ordersSubmitDTO.getAddressBookId());
        // 地址为空
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 校验购物车
        List<ShoppingCart> shoppingCartList = shoppingCartService.list();
        // 购物车为空
        if (shoppingCartList == null || shoppingCartList.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        // 判断菜品和套餐是否在售卖中
        List<String> listStatus = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            // 如果是套餐
            if (shoppingCart.getSetmealId() != null && shoppingCart.getSetmealId()!= 0) {
                String byIdStatus = setmealService.getByIdStatus(shoppingCart.getSetmealId(), StatusConstant.DISABLE);
                if (byIdStatus != null) {
                    listStatus.add(byIdStatus);
                }
            }
            // 如果是菜品
            if (shoppingCart.getDishId() != null && shoppingCart.getDishId() != 0) {
                String byIdStatus = dishService.getByIdStatus(shoppingCart.getDishId(), StatusConstant.DISABLE);
                if (byIdStatus != null) {
                    listStatus.add(byIdStatus);
                }
            }
        }
        if (listStatus.size() > 0 && listStatus!= null) {
            throw new BaseException(listStatus.toString() + "已停售");
        }

        // 判断用户地址与商家地址之间的距离
        String usershop = addressBook.getProvinceName() + addressBook.getCityName() + addressBook.getDistrictName() + addressBook.getDetail();
        log.info("用户地址：{}", usershop);
        baiDuAPIService.compute(usershop);


        // 实际订单金额，获取购物车中所有的菜品金额总和
//        BigDecimal amounts = new BigDecimal(0);
//        for (ShoppingCart shoppingCart : shoppingCartList) {
//            amounts = amounts.add(shoppingCart.getAmount());
//        }

        // 订单表插入数据，返回订单id
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        // 下订单时间
        orders.setOrderTime(LocalDateTime.now());
        // 订单状态
        orders.setStatus(orders.PENDING_PAYMENT);
        // 支付状态
        orders.setPayStatus(orders.UN_PAID);
        // 下单用户id
        orders.setUserId(BaseContext.getCurrentId());
        // 订单号 获取当前时间戳(毫秒)
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        // 收货人
        orders.setConsignee(addressBook.getConsignee());
        // 手机号
        orders.setPhone(addressBook.getPhone());
        // 地址
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null? "" : addressBook.getDetail()));
        log.info("订单信息：{}", orders);
        orderMapper.insert(orders);

        // 订单明细表插入菜品套餐数据 购物车数据shoppingCartList
        for (ShoppingCart shoppingCart : shoppingCartList) {
            log.info("购物车数据：{}", shoppingCart);
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            // 订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailMapper.insert(orderDetail);
        }

        // 清空购物车
        log.info("清空购物车");
        shoppingCartService.clean();

        // 封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .build();
        return orderSubmitVO;
    }

    /**
     * 历史订单查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 获取用户id
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        // 设置分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        // 分页查询
        Page<OrderVO> page = orderMapper.pageQuery(ordersPageQueryDTO);
        List<OrderVO> list = new ArrayList<>();
        // 如果有历史订单，封装订单详细数据
        if ( page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                // 订单ID
                Long id = orders.getId();
                // 查询订单下的订单明细
                List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                list.add(orderVO);
            }
        }
        long total = page.getTotal();
        return new PageResult(page.getTotal(),list);
    }

    /**
     * 订单详情查询
     * @param id
     * @return
     */
    @Override
    public OrderVO getByIdOrderDetail(Long id) {
        // 订单明细
        List<OrderDetail> byOrderId = orderDetailMapper.getByOrderId(id);
        if (byOrderId != null && byOrderId.size() > 0) {
            OrderVO orderVO = new OrderVO();
            // 订单基本信息
            Orders orders = orderMapper.getById(id);
            BeanUtils.copyProperties(orders, orderVO);
            // 订单菜品信息
            orderVO.setOrderDetailList(byOrderId);
            return orderVO;
        }
        return null;
    }

    /**
     * 取消订单
     * - 待支付和待接单状态下，用户可直接取消订单
     * - 商家已接单状态下，用户取消订单需电话沟通商家
     * - 派送中状态下，用户取消订单需电话沟通商家
     * - 如果在待接单状态下取消订单，需要给用户退款
     * - 取消订单后需要将订单状态修改为“已取消”
     * @param id
     * @return
     */
    @Override
    public void cancel(Long id) {
        // 获取订单信息
        Orders orders = getOrderStatus(id);

        // 待支付和待接单状态下，用户可直接取消订单,剩下状态都不允许直接改换状态，需要联系商家
        if ( orders.getStatus() > 2 ) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders newOrders = new Orders();
        // 设置订单id
        newOrders.setId(orders.getId());

        //如果在待接单状态下取消订单，需要给用户退款
        if ( orders.getStatus() == Orders.TO_BE_CONFIRMED ) {
            // 调用微信退款接口
            log.info("调用微信退款接口");
            // 修改支付状态
            newOrders.setPayStatus(Orders.REFUND);
        }
        // 修改订单状态
        newOrders.setStatus(Orders.CANCELLED);
        // 修改取消原因
        newOrders.setCancelReason("用户取消");
        // 修改取消时间
        newOrders.setCancelTime(LocalDateTime.now());

        log.info("订单{}取消，修改订单状态为{}",newOrders);
        orderMapper.cancel(newOrders);
        log.info("订单{}取消成功",newOrders.getId());
    }

    @Override
    public void repetition(Long id) {
        // 获取订单信息
        Orders orders = getOrderStatus(id);

        // 获取订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        // 订单明细添加到购物车
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCartDTO shoppingCartDTO = new ShoppingCartDTO();
            BeanUtils.copyProperties(orderDetail, shoppingCartDTO);
            shoppingCartService.add(shoppingCartDTO);
        }
    }

    /**
     * 订单分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> page = orderMapper.pageQuery(ordersPageQueryDTO);

        long total = page.getTotal();
        List<OrderVO> records = page.getResult();
        return new PageResult(total, records);
    }

    /**
     * 统计订单信息
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        return orderMapper.statistics(Orders.TO_BE_CONFIRMED, Orders.CONFIRMED,Orders.DELIVERY_IN_PROGRESS);
    }

    /**
     * 订单状态修改 接收
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        // 获取订单信息
        Orders orders = getOrderStatus(ordersConfirmDTO.getId());
        
        // 订单状态不为待接单，则不能确认订单
        if (orders.getStatus() != Orders.TO_BE_CONFIRMED) { 
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 修改订单状态为待派送
        ordersConfirmDTO.setStatus(Orders.CONFIRMED);
        orderMapper.confirm(ordersConfirmDTO);
    }

    /**
     * 订单状态修改 拒绝
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        // 获取订单信息
        Orders orders = getOrderStatus(ordersRejectionDTO.getId());
        if (orders.getStatus() > Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 订单状态为待接单，则执行用户退款
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED) {
            log.info("调用微信退款接口");
            // 修改支付状态为退款
            orders.setPayStatus(Orders.REFUND);
        }
        // 修改订单状态为取消
        orders.setStatus(Orders.CANCELLED);
        // 设置拒单原因
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        // 设置取消时间
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.cancel(orders);
    }

    /**
     * 订单状态修改 取消
     * @param ordersCancelDTO
     */
    @Override
    public void Cancel(OrdersCancelDTO ordersCancelDTO) {
        // 获取订单信息
        Orders orders = getOrderStatus(ordersCancelDTO.getId());
        // 订单状态为待接单或已取消，则不能取消
        if (orders.getStatus() == Orders.TO_BE_CONFIRMED || orders.getStatus() == Orders.CANCELLED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 修改订单状态为取消
        orders.setStatus(Orders.CANCELLED);
        // 设置取消原因
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        // 设置取消时间
        orders.setCancelTime(LocalDateTime.now());

        // 订单状态不为待付款，则执行用户退款
        if (orders.getStatus() != Orders.PENDING_PAYMENT) {
            log.info("调用微信退款接口");
            // 修改支付状态为退款
            orders.setPayStatus(Orders.REFUND);
        }
        orderMapper.cancel(orders);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        // 获取订单信息
        Orders orders = getOrderStatus(id);
        if (orders.getStatus() != Orders.CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 修改订单状态为派送中
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orderMapper.cancel(orders);
    }

    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        // 获取订单信息
        Orders orders = getOrderStatus(id);
        if (orders.getStatus() != Orders.DELIVERY_IN_PROGRESS) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 修改订单状态为派送中
        orders.setStatus(Orders.COMPLETED);
        orderMapper.cancel(orders);
    }

    @Override
    public Orders payment(OrdersPaymentDTO ordersPaymentDTO) {
        // 根据订单号获取订单信息
        Orders orders = orderMapper.getByOrderNumber(ordersPaymentDTO);
        // 订单状态不为待支付，则不能支付
        if (orders.getStatus()!= Orders.PENDING_PAYMENT || orders.getPayStatus()!= Orders.UN_PAID) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 订单号不存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 调用微信支付接口
        log.info("调用微信支付接口");


        // 订单状态修改为待接单
        orders.setStatus(Orders.TO_BE_CONFIRMED);
        // 修改支付状态为已支付
        orders.setPayStatus(Orders.PAID);
        // 修改支付方式为微信支付
        orders.setPayMethod(ordersPaymentDTO.getPayMethod());
        // 修改支付时间
        orders.setCheckoutTime(LocalDateTime.now());
        // 修改预计送达时间
        orders.setEstimatedDeliveryTime(LocalDateTime.now().plusMinutes(30));
        orderMapper.payment(orders);

        // 通过websock发送消息给客户端
        log.info("通过websock发送消息给客户端");
        Map map = new HashMap();
        map.put("type",1); // 1表示来单提醒 2表示客户催单
        map.put("orderId",orders.getId());
        map.put("content",orders.getNumber());

        // 转换成json格式
        String json = JSON.toJSONString(map);

        // 发送消息
        webSocketServer.sendToAllClient(json);

        return orders;
    }

    @Override
    public void reminder(Long id) {
        // 获取订单信息
        Orders orders = getOrderStatus(id);
        // 订单状态不为待接单，则不能催单
        if (orders.getStatus()!= Orders.TO_BE_CONFIRMED) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 通过websock发送消息给客户端
        log.info("通过websock发送消息给客户端");
        Map map = new HashMap();
        map.put("type",2); // 1表示来单提醒 2表示客户催单
        map.put("orderId",orders.getId());
        map.put("content",orders.getNumber());

        // 转换成json格式
        String json = JSON.toJSONString(map);

        // 发送消息
        webSocketServer.sendToAllClient(json);


    }


    /**
     * 获取订单信息，验证订单是否存在
     * @param id
     * @return orders
     */
    private Orders getOrderStatus(Long id) {
        // 获取订单信息
        Orders orders = orderMapper.getById(id);
        // 校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        } 
        return orders;
    }
}
